package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author mff
 * @date 2022/6/11 11:26
 * @mood happy
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    //    添加菜品
    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dishDto) {
//        将数据保存到dish表
        dishService.save(dishDto);
//        获得Flavour的数据并保存到dish_flavor表
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.stream().map((item) -> {
                item.setDishId(dishId);
                return item;
            }).collect(Collectors.toList());
            dishFlavorService.saveBatch(flavors);
        }
        return R.success("添加成功");
    }

//    接口四：分页查询菜品数据

    @GetMapping("/page")
    public R<Page<DishDto>> saveDishWithFlavour(int page, int pageSize, String name) {  // name用于条件分页查询
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

//        创建条件查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(name != null, Dish::getName, name).orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        log.info("===================执行==========================");
        dishService.page(dishPage,dishLambdaQueryWrapper);
        log.info("===================执行==========================");


//        复制基本内容
            BeanUtils.copyProperties(dishPage, dishDtoPage);

//        获得口味数据
        List<Dish> records = dishPage.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
//            设置口味的基本数据
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category dishCategory = categoryService.getById(categoryId);
            if (dishCategory != null) {
//                设置类型名
                dishDto.setCategoryName(dishCategory.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

//        设置口味信息
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

//    接口五:修改菜品数据
//    接口5.1、根据id查询菜品数据，用于回显
    @GetMapping("/{dishId}")
    public R<DishDto> backDish(@PathVariable Long dishId){
        Dish dish = dishService.getById(dishId);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

//        查询该菜品对应的口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(dishId != null, DishFlavor::getDishId, dishId);
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

//    接口5.2修改菜品  ,先删除再添加
    @PutMapping
    public R<DishDto> updateDishWithFlavour(@RequestBody DishDto dishDto){
//        先修改原来dish表中的数据,使用update()
        log.info("============================开始更新======================================");
        dishService.updateById(dishDto);
        log.info("============================结束更新======================================");
//        再修改口味信息,先删除再新增
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(dishDto.getId() != null, DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

//        再添加
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        return R.success(dishDto);
    }

//    接口六：批量删除

    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){
//        先删除dish表
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(ids != null, Dish::getId, ids);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);

        for (Dish item : list) {
            if (item.getStatus() == 0) {
                dishService.removeById(item.getId());
                //        再删除dishFlavor表
                LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishFlavorLambdaQueryWrapper.eq(item.getId() != null, DishFlavor::getDishId, item.getId());
                dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
            }else if (item.getStatus() == 1){
                return R.error("该商品正在售卖,无法删除");
            }
        }
/*        list.stream().map((item) -> {
            if (item.getStatus() == 0) {
                dishService.removeById(item.getId());
                //        再删除dishFlavor表
                LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishFlavorLambdaQueryWrapper.eq(item.getId() != null, DishFlavor::getDishId, item.getId());
                dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
                return item;
            }else if (item.getStatus() == 1){
                return R.error("该商品正在售卖,无法删除");
            }
            return item;
        }).collect(Collectors.toList());*/
        return R.success("删除成功");
    }


//    批量修改售卖状态
    @PostMapping("/status/{statue}")
    public R<String> modifyStatus(@PathVariable int statue,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Dish::getStatus, statue);
        lambdaUpdateWrapper.in(Dish::getId, ids);
        log.info("=========================================================================");
        dishService.update(lambdaUpdateWrapper);
        log.info("=========================================================================");
        return R.success("修改成功");
    }

    //    根据分类id查询该分类下的所有菜品集合
/*    @GetMapping("/list")
    public R<List<Dish>> findDishByCategory(Long categoryId){
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        return R.success(list);
    }*/

    //    新增套餐
//    1、查询分类表category表中所有的套餐分类： /category/list?type=2 【已完成】
//    2、根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    public R<List<DishDto>> getDishList(Dish dish){
        List<DishDto> listWithFlavour = null;
//        在查询数据库之前先查询缓存中是否有需要的dish数据
//        制动态且唯一的key用于存储信息(标志+分类ID+状态)，这里读取的是全部的菜品
        String key ="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        从redis中获取，若有则直接获取并返回，若无则查询数据库后加入缓存，并设置存活时间
        listWithFlavour = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (listWithFlavour!=null){
            return R.success(listWithFlavour);
        }


        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.orderByDesc(Dish::getSort);
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        listWithFlavour = new ArrayList<>();
        for (Dish item : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(flavors);
            listWithFlavour.add(dishDto);
        }

//        redis中没有则将查询到的数据缓存到redis
        redisTemplate.opsForValue().set(key,listWithFlavour,60, TimeUnit.MINUTES);
//        1、这里有个必要再取一次么？
        listWithFlavour = (List<DishDto>) redisTemplate.opsForValue().get(key);
        return R.success(listWithFlavour);
    }

}
